<template>
  <el-dialog v-model="visible" title="按时间重新推送面单" width="500">
    <el-form :model="form" :rules="rules" ref="formRef" label-width="80px">
      <el-form-item label="起始时间" prop="start_time">
        <div style="display: flex; gap: 8px; align-items: center">
          <el-date-picker
            v-model="form.start_time"
            type="datetime"
            style="width: 180px"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="请选择开始时间"
          />
        </div>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="visible = false">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确认提交</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup name="LabelRePushForm">
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'

// 控制弹窗显示
const visible = ref(false)

// 表单模型
const form = ref({
  start_time: null
})

// 表单引用
const formRef = ref()

// 自定义校验器：时间不能超过 maxDays 天前
const createStartDateValidator = (maxDays) => {
  return (rule, value, callback) => {
    if (!value) return callback(new Error('请选择开始时间'))

    const selectedDate = new Date(value)
    const now = new Date()
    const diffDays = (now - selectedDate) / (1000 * 60 * 60 * 24)

    if (diffDays > maxDays) {
      return callback(new Error(`开始时间不能早于当前时间的 ${maxDays} 天之前`))
    }

    callback()
  }
}

// 表单校验规则
const rules = {
  start_time: [
    { required: true, message: '请选择时间', trigger: 'change' },
    { validator: createStartDateValidator(60), trigger: 'change' }
  ]
}

function getStartOfDayNDaysAgo(n = 0) {
  const date = new Date()
  date.setDate(date.getDate() - n)
  date.setHours(0, 0, 0, 0)

  const yyyy = date.getFullYear()
  const mm = String(date.getMonth() + 1).padStart(2, '0')
  const dd = String(date.getDate()).padStart(2, '0')
  const hh = '00'
  const min = '00'
  const ss = '00'

  return `${yyyy}-${mm}-${dd} ${hh}:${min}:${ss}`
}

// 向父组件暴露的打开方法
function open() {
  form.value.start_time = getStartOfDayNDaysAgo()
  visible.value = true
}

// 发出 confirm 事件的处理方法
const emit = defineEmits(['confirm'])

function handleConfirm() {

  formRef.value.validate((valid) => {
  if (!valid) return
    emit('confirm', { ...form.value })
    visible.value = false
  })
}

defineExpose({ open })

onMounted(() => {
  // 初始化逻辑（如果有需要）
})
</script>
